package com.lbs.jiepiaisi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.adapter.EquipSearchAdapter;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.bean.EquipBean;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.utils.Constant1;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.SpUtil;
import com.lbs.jiepiaisi.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yu on 2020-01-07 9:07.
 * Description:
 */

public class EquipSearchActivity extends BaseActivity implements TextWatcher{

    private EditText mEditText;
    private Handler mHandler;
    private SearchTask mSearchTask;//搜索任务
    private String keyword;
    private RecyclerView recyclerView;
    private EquipSearchAdapter mAdapter;
    private LinearLayout mProgressbar;
    private String deptId;
    private List<EquipBean.Result.Items> items = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equip_search);
        deptId = (String)SpUtil.get(Constant1.UNDERLING_DEPTID,"");

        findView();
        setListner();
        initData();
    }

    private void setListner() {
        findViewById(R.id.tv_cancel).setOnClickListener(v -> finish());

        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            EquipBean.Result.Items item = items.get(position);

            if (item.getPoint().getLat() == null || item.getPoint().getLng() == null) {
                ToastUtil.show("该设备未定位");
                return;
            }

            if (item.getMark().equals("D")) {
                ToastUtil.show("该设备已被禁用");
                return;
            }

            Intent intent = new Intent(this,PlatformMainActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("item",item);
            intent.putExtras(bundle);
            setResult(1000,intent);
            finish();
        });
    }

    private void findView() {
        mEditText = findViewById(R.id.edit_search);
        showSoftInputFromWindow(mEditText);
        mEditText.addTextChangedListener(this);

        recyclerView = findViewById(R.id.recyclerView);

        mAdapter = new EquipSearchAdapter(R.layout.list_item_search, items);
        mAdapter.bindToRecyclerView(recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter);

        mProgressbar = findViewById(R.id.progressbar);

    }
    private void initData() {
        size = 99999;
        mHandler = new Handler();
        mSearchTask = new SearchTask();
    }
    /**
     * @param charSequence 输入框中改变前的字符串信息
     * @param start 输入框中改变前的字符串的起始位置
     * @param count 输入框中改变前后的字符串改变数量一般为0
     * @param after 输入框中改变后的字符串与起始位置的偏移量
     */
    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {}
    /**
     * @param charSequence 输入框中改变后的字符串信息
     * @param start 输入框中改变后的字符串的起始位置
     * @param before 输入框中改变前的字符串的位置 默认为0
     * @param count 输入框中改变后的一共输入字符串的数量
     */
    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
        if(charSequence.length() > 0) {
            mHandler.removeCallbacks(mSearchTask);
            mHandler.postDelayed(mSearchTask,800);
        } else {
            mHandler.removeCallbacks(mSearchTask);
        }
    }
    /**
     * @param editable 输入结束呈现在输入框中的信息
     */
    @Override
    public void afterTextChanged(Editable editable) {
        keyword = editable.toString();
    }

    /**
     * 搜索任务
     */
    public class SearchTask implements Runnable {
        @Override
        public void run() {
            hideEmpty();
            showProgress();
            reset();
            refresh();
        }

        private void reset() {
            items.clear();
        }

        private void showProgress() {
            mProgressbar.setVisibility(View.VISIBLE);
        }

        private void hideProgress() {
            mProgressbar.setVisibility(View.GONE);
        }

        private void showEmpty() {
            View view = LayoutInflater.from(mContext).inflate(R.layout.layout_empty, null);
            mAdapter.setEmptyView(view);
        }

        private void hideEmpty() {
            View view = LayoutInflater.from(mContext).inflate(R.layout.layout_empty1, null);
            mAdapter.setEmptyView(view);
        }

        public void refresh() {
            Api.getInstance().createService()
                    .loadEquipList(deptId,page,size,"",keyword)
                    .compose(RxSchedulers.observableIO2Main(mContext))
                    .subscribe(new ProgressObserver<EquipBean>(mContext,false) {
                        @Override
                        public void onSuccess(EquipBean result) {
                            hideProgress();
                            List<EquipBean.Result.Items> item = result.getResult().get(0).getItems();
                            if (item.size() == 0) showEmpty();
                            items.addAll(item);
                            mAdapter.setNewData(items);
                        }

                        @Override
                        public void onFailure(ErrorException e) {
                            hideProgress();
                        }
                    });
        }
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public  void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}
